package gdut.community.controller;

import gdut.community.entity.Comment;
import gdut.community.entity.DiscussPost;
import gdut.community.entity.Event;
import gdut.community.entity.User;
import gdut.community.event.EventProducer;
import gdut.community.service.LikeService;
import gdut.community.util.CommunityConstant;
import gdut.community.util.CommunityUtil;
import gdut.community.util.HostHolder;
import gdut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {
    @Resource
    private LikeService likeService;

    @Resource
    private HostHolder hostHolder;

    @Resource
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/like",method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId,int entityUserId,int postId){
        User user =hostHolder.getUser();

        //实现点赞
        likeService.like(user.getId(),entityType,entityId,entityUserId);

        //统计点赞的数量和点赞的状态，用来回显
        long likeCount=likeService.findEntityLikeCount(entityType,entityId);

        //状态
        int likeStatus=likeService.findEntityLikeStatus(user.getId(),entityType,entityId);

        //存入map，用json传送
        Map<String,Object> map=new HashMap<>();

        map.put("likeCount",likeCount);
        map.put("likeStatus",likeStatus);

        //完成点赞后，触发点赞事件
        //触发事件之前需要构造事件对象
        if (likeStatus==1){//只有在点赞的时候才去触发这个事件，取消点赞就不要去恶心别人了
            Event event=new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId",postId);
            //处理事件
            eventProducer.fireEvent(event);
        }

        if(entityType == ENTITY_TYPE_POST) {
            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }

        return CommunityUtil.getJSONString(0,null,map);
    }
}
